//
//  HORepaireDoneViewController.m
//  微度报修
//
//  Created by foguo-mac-1 on 7/4/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HORepaireDoneViewController.h"
#import "HOConstants.h"
#import "HOEditView.h"
#import "HOUtils.h"
#import "HOReportOrderEntity.h"
#import "HOStatusEntity.h"
#import "HOStatusTableViewCell.h"

@interface HORepaireDoneViewController ()<HOEditViewDelegate, UITextViewDelegate, UITextFieldDelegate>
@property(nonatomic, retain)HOEditView *replyEditView;
@property(nonatomic, retain)UITextField *costTextField;
@property(nonatomic, retain)HOReportOrderEntity *orderEntity;
@property(nonatomic, retain)NSObject *focusedText;
@end

@implementation HORepaireDoneViewController


- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view.
	[self initTableView];
	[self initSubviews];
	[self initMediaViewOnlyImageDiaplay];
	[self initTableViewFooterViewWithTitle:NSLocalizedString(@"确认维修完成", @"确认维修完成")];
	[self registerTapGesture];
	[self registerKeyboard];
}

- (void)initSubviews
{
	self.replyEditView = [[[HOEditView alloc] initWithFrame:CGRectMake(0,
																	   0,
																	   self.view.frame.size.width,
																	   134)] autorelease];
	self.replyEditView.limitedCount = 120;
	self.replyEditView.delegate = self;
	self.replyEditView.layer.cornerRadius = 0;
	self.replyEditView.layer.borderWidth = 0;
	[self.replyEditView.layer setMasksToBounds:YES];
	[self.replyEditView setPlaceHolder:NSLocalizedString(@"故障描述(默认'维修完成')", @"故障描述(默认'维修完成')")];
	[self.replyEditView getTextView].returnKeyType = UIReturnKeySend;
//	[self.replyEditView getTextView].delegate = nil;
	
	self.costTextField = [[[UITextField alloc]
						  initWithFrame:CGRectMake(130,
												   (44 - 30) / 2,
												   100,
												   30)] autorelease];
	self.costTextField.placeholder = NSLocalizedString(@"维修金额", @"维修金额");
//	self.costTextField.layer.borderWidth = [HOUtils defaultOnePixelConversion];
	self.costTextField.font = [UIFont systemFontOfSize:15];
	self.costTextField.keyboardType = UIKeyboardTypeNumberPad;
	self.costTextField.textColor = TEXT_COLOR_181818;
	self.costTextField.delegate = self;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
	self.focusedText = self.costTextField;
	return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
	return YES;
}

- (void)hideKeyboard
{
	self.focusedText = nil;
	[[self.replyEditView getTextView] resignFirstResponder];
	[self.costTextField resignFirstResponder];
}

- (void)requestData
{
	[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_CheckOrderStatus,
								  kHO_FIELD_OrderId:[NSNumber numberWithInt:self.orderId]}];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
	[self hideKeyboard];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	[self setNavigationItemTitle:NSLocalizedString(@"维修完成", @"维修完成")];
	[self requestData];
}

- (void)dealloc
{
	self.orderEntity = nil;
	self.replyEditView = nil;
	[super dealloc];
}


- (void)didClickFooterButton:(UIButton *)btn
{
	self.view.userInteractionEnabled = NO;
	[self convertingVoice];
}

- (void)submit
{
	NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[self getMediaDic]];
	
	NSString *money = [self getTrimingCharaFromTextField:self.costTextField];
	if(money.length == 0)
	{
		money = @"0";
	}
	
	NSString *content = [self getTrimingCharaFromTextView:[self.replyEditView getTextView]];
	if(content.length == 0)
	{
		content = @"维修完成";
	}
	
	if(self.isAssistantReport)
	{
		[dic setObject:kHO_ACTION_AssistantFaultComplete forKey:kHO_FIELD_Action];
	}
	else
	{
		[dic setObject:kHO_ACTION_FaultComplete forKey:kHO_FIELD_Action];
	}
	[dic setObject:content forKey:kHO_FIELD_Content];
	[dic setObject:money forKey:kHO_FIELD_FaultMoney];
	[dic setObject:[NSNumber numberWithInt:self.orderId] forKey:kHO_FIELD_OrderId];
	[self sendRequestWithParams:dic];
	
	

}


#pragma mark - -- UITableViewDelegate/UITableViewDataResource implement methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(indexPath.section == 0)
		return 44;
	else if(indexPath.section == 1)
		return 58;
	else if(indexPath.section == 2)
	{
		if(indexPath.row == 1)
		{
			return [self getPhotoViewHeight];
		}
		else
		{
			return 0;// self.isRecordModal ?  190: 50;
		}
	}
	return 134;
}

- (void)onKeyboardWillShow:(NSNotification *)notification
{
	[super onKeyboardWillShow:notification];
	if(self.focusedText == self.costTextField)
	{
		[baseTableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

	}
	else
	{
		[baseTableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2] atScrollPosition:UITableViewScrollPositionTop animated:YES];

	}
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return 4;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	if(section == 0)
		return 2;
	if(section == 1)
		return 4;
	else if(section == 2)
		return 2;
	return 1;
}


- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return SECTION_PADDING / 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(indexPath.section == 0)
	{
		static NSString *HOReplyTableViewCell = @"HOReplyTableViewCell";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:HOReplyTableViewCell];
//		if(cell == nil)
		{
			cell = [[[HOTableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: HOReplyTableViewCell] autorelease];
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		UILabel *lbl = (UILabel *)[cell viewWithTag:115];
		if(lbl == nil)
		{
			lbl = [[UILabel alloc]
				   initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
											(44 - 22) / 2,
											200,
											22)];
			lbl.text = @"订单号：3128";
			lbl.textColor = TEXT_COLOR_181818;
			lbl.font = [UIFont systemFontOfSize:15];
			[cell.contentView addSubview:lbl];
			lbl.tag = 115;
			[lbl release];
		}
		lbl = (UILabel *)[cell viewWithTag:115];
		if(indexPath.row == 0)
		{
			lbl.text = [NSString stringWithFormat:@"%@%d", NSLocalizedString(@"订单号：", @"订单号："),self.orderEntity.orderSN];
		}
		else
		{
			lbl.text = NSLocalizedString(@"请输入维修费用", @"请输入维修费用");
			UITextField *textField = (UITextField *)[cell viewWithTag:334];
			if(textField == nil)
			{
				
				UIView *view = [[[UIView alloc]
								initWithFrame:CGRectMake(self.costTextField.frame.origin.x - HO_HORIZONAL_PADDING,
														 self.costTextField.frame.origin.y - 1,
														 self.costTextField.frame.size.width + 2 * HO_HORIZONAL_PADDING,
														 self.costTextField.frame.size.height + 2)] autorelease];
				[view setBackgroundColor:[UIColor clearColor]];
				view.layer.borderWidth = [HOUtils defaultOnePixelConversion];
				view.layer.borderColor = MAIN_COLOR_NORMAL.CGColor;
				[cell.contentView addSubview:view];
				
				textField = self.costTextField;
				self.costTextField.tag = 334;
				[cell.contentView addSubview:textField];
				
				
				
				UILabel *lbl = [[[UILabel alloc]
								initWithFrame:CGRectMake(view.frame.origin.x + view.frame.size.width + 5,
														 self.costTextField.frame.origin.y - 1,
														 self.costTextField.frame.size.width + 2 * HO_HORIZONAL_PADDING,
														 self.costTextField.frame.size.height + 2)] autorelease];
				lbl.text = NSLocalizedString(@"元", @"元");
				lbl.textColor = TEXT_COLOR_181818;
				lbl.font = [UIFont systemFontOfSize:15];
				[cell.contentView addSubview:lbl];
			}
			
		}
		return cell;
	}
	else if(indexPath.section == 1)
	{
		static NSString *HOReplyTableViewCell = @"HOReplyTableViewCell3";
		HOStatusTableViewCell *cell = (HOStatusTableViewCell *)[tableView dequeueReusableCellWithIdentifier:HOReplyTableViewCell];
//		if(cell == nil)
		{
			cell = [[[HOStatusTableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: HOReplyTableViewCell] autorelease];
			[cell initWithWidth:tableView.frame.size.width withHeight:58];
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		HOStatusEntity *statusEntity = nil;
		if(indexPath.row < [self.orderEntity.statusList count])
		{
			statusEntity = [self.orderEntity.statusList objectAtIndex:indexPath.row];
		}
		if(indexPath.row == 0)
		{
			cell.statusLbl.text = NSLocalizedString(@"未受理", @"未受理");
			
		}
		else if(indexPath.row == 1)
		{
			cell.statusLbl.text = NSLocalizedString(@"已受理", @"已受理");
		}
		else if(indexPath.row == 2)
		{
			cell.statusLbl.text = NSLocalizedString(@"维修完成", @"维修完成");
		}
		else if(indexPath.row == 3)
		{
			cell.statusLbl.text = NSLocalizedString(@"确认完成", @"确认完成");
		}
		if(statusEntity)
		{
			cell.contentLbl.text = [NSString stringWithFormat:@"%@%@", NSLocalizedString(@"维修人:", @"维修人:"), statusEntity.repairmanName];
			cell.timeLbl.text = [HOUtils getDateFromTimeInterval:statusEntity.createTime * 1000];
			cell.contentLbl.hidden = NO;
			cell.timeLbl.hidden = NO;
		}
		[cell setHightLight:statusEntity != nil];
		return cell;
		return cell;
		
	}
	else if(indexPath.section == 2)
	{
		UITableViewCell *cell = [self tableView:tableView cellForQuickTakePhotoRowAtIndexPath:indexPath];
		UIView *view = (UIView *)[cell.contentView viewWithTag:216];
		UIView *view1 = (UIView *)[cell.contentView viewWithTag:117];
		view.hidden = YES;
		view1.hidden = YES;
		return cell;
	}
	else if(indexPath.section == 3)
	{
		static NSString *HOReplyTableViewCell = @"HOReplyTableViewCell";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:HOReplyTableViewCell];
		if(cell == nil)
		{
			cell = [[[HOTableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: HOReplyTableViewCell] autorelease];
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		HOEditView *editView = (HOEditView *)[cell viewWithTag:117];
		if(editView == nil)
		{
			self.replyEditView.tag = 117;
			[cell.contentView addSubview:self.replyEditView];
		}
		return cell;
	}
	return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	if(indexPath.section == 1)
	{
		self.orderEntity.status = (HO_REPORT_ORDER_STATUS) indexPath.row + 1;
		[baseTableview reloadData];
	}
	
}
#pragma mark

- (HOEditTableViewCell *)tableView:(UITableView *)tableView cellForEditRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *AMBaseTableViewCellIdentifier = @"HOTableViewCell";
	HOEditTableViewCell *cell = (HOEditTableViewCell *)[tableView dequeueReusableCellWithIdentifier:AMBaseTableViewCellIdentifier];
	if(cell == nil)
	{
		cell = [[[HOEditTableViewCell alloc]
				 initWithStyle:UITableViewCellStyleDefault
				 reuseIdentifier: AMBaseTableViewCellIdentifier] autorelease];
	}
	return cell;
}
#pragma mark -- tool
- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

- (void)didReceiveCommand:(NSString *)action data:(id)data
{
	if([action isEqualToString:kHO_CMD_ReceiveNotificationMessage])
	{
		NSDictionary *dic = [data objectForKey:kHO_FIELD_Extras];
		int type = [[dic valueForKey:kHO_FIELD_SendType] intValue];
		int orderId = [[dic valueForKey:kHO_FIELD_OrderId] intValue];
		if(type == HO_NC_TYPE_ORDER_ASSIGNED && orderId == self.orderEntity.orderId)
		{
			[self requestData];
		}
	}
}

- (void)requestDidSuccessWithResponse:(HOBaseResponseEntity *)response
{
	if([response isEqualAction:kHO_ACTION_FaultComplete])
	{
		self.view.userInteractionEnabled = NO;
		[self sendCommand:kHO_CMD_Report_Detail_Changed data:nil];
		[self popupHintView:NSLocalizedString(@"维修完成!", @"提交成功!") inTime:1.5 needCallback:YES];
	}
	if([response isEqualAction:kHO_ACTION_AssistantFaultComplete])
	{
		self.view.userInteractionEnabled = NO;
		[self sendCommand:kHO_CMD_Report_Detail_Changed data:nil];
		[self popupHintView:NSLocalizedString(@"维修完成!", @"维修完成!") inTime:1.5 needCallback:YES];
	}
	else if([response isEqualAction:kHO_ACTION_CheckOrderStatus])
	{
		if(self.orderEntity == nil)
		{
			self.orderEntity = [[[HOReportOrderEntity alloc] init] autorelease];
			[self.orderEntity parseDic:response.dataNode];
			[baseTableview reloadData];
		}
	}
}

- (void)hintDidHide
{
	self.view.userInteractionEnabled = YES;
	[self goBack];
}

@end
